/**
 * @file 全局拦截器
 * @version 1.0.0
 * @author qingxue
 * @createDate 2024-04-06 20:00
 * @updateDate 2024-04-06 20:00
 */

const tokenConfig = require('@/config/base.config').security.token;
const { ResponseBody, ErrorMessage } = require('@/utils/response');
const { verify } = require('@/utils/permission/jwt');
const { getUserPermissionById } = require('@/services/user_service');

module.exports = function (app) {
  app.use(async (req, res, next) => {
    // 登录鉴权
    if (tokenConfig.enableToken) {
      // 白名单放行
      if (tokenConfig.whiteList.includes(req.path)) {
        next();
        return;
      }
      const token = req.headers[tokenConfig.header];
      // token 不存在，返回错误
      if (!token) {
        res.status(401).json(ResponseBody.error(ErrorMessage.TokenNotFoundError, null));
        return;
      }
      // 验证 token
      const userId = verify(token);
      if (!userId) {
        res.status(401).json(ResponseBody.error(ErrorMessage.TokenExpiredError, null));
        return;
      }
      // 获取用户权限等级
      req['customData'] = {
        userId,
        level: await getUserPermissionById(userId)
      };
    }
    // 放行
    next();
  });
};
